package com.mesSystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mesSystem.dto.Result;
import com.mesSystem.entity.Material;
import com.mesSystem.service.impl.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RequestMapping("/product")
@Controller
@ResponseBody
public class MaterialController {
    @Autowired
    MaterialService materialService;

    @PostMapping("increase")
    public Result increase(@RequestBody Material material) {
        material.setCreateTime(LocalDateTime.now());
        material.setUpdateTime(LocalDateTime.now());
        materialService.save(material);
        log.info("新增产品信息为：{}", material);
        return Result.ok("保存成功～");
    }

    @DeleteMapping("delete")
    public Result delete(Long MaterialId) {
        materialService.removeById(MaterialId);
        log.info("删除：{}成功",MaterialId);
        return Result.ok("删除成功");
    }
//
//    /**
//     * 查询所有信息并转换为list集合
//     * @return
//     */
//    @GetMapping("list")
//    public Result queryMaterial() {
//        List<Material> materials = materialService
//                .query().orderByAsc("material_id").list();
//        log.info("被查询信息为：{}", materials);
//        return Result.ok(materials);
//    }

    /**
     * 分页查询材料信息
     */
    @GetMapping("query")
    public Result queryMaterial(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "size", defaultValue = "10") Integer size) {
        // 创建分页器对象
        Page<Material> materialPage = new Page<>(page, size);

        // 调用分页查询方法，将分页器传递给service
        materialService.page(materialPage, new QueryWrapper<Material>().orderByAsc("material_id"));

        // 从分页器对象中获取分页后的数据
        List<Material> materials = materialPage.getRecords();

        log.info("被查询信息为：{}", materials);

        // 返回分页结果
        return Result.ok(materials);
    }


    @PostMapping("update")
    public Result update(@RequestBody Material material) {
        //设置更新时间
        material.setUpdateTime(LocalDateTime.now());
        materialService.updateById(material);
        log.info("更新了:{}", material);
        return Result.ok("更新成功");
    }

}
